import { Effect, Reducer, Subscription } from 'umi';
import { tableApi } from '@/utils/api';

export interface IndexModelState {
  cityTableData: any[];
  total: number;
  isModalVisible: boolean;
}

export interface IndexModelType {
  namespace: 'city';
  state: IndexModelState;
  effects: {
    getTableDataAsync: Effect;
  };
  reducers: {
    getTableData: Reducer;
    open: Reducer;
    close: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'city',

  state: {
    cityTableData: [],
    total: 0,
    isModalVisible: false,
  },

  effects: {
    *getTableDataAsync({ payload }, { call, put }) {
      const res = yield call(() => tableApi(payload));
      yield put({
        type: 'getTableData',
        payload: res,
      });
    },
  },
  reducers: {
    getTableData(state, action) {
      const result = action.payload.result.map((item: any) => {
        return {
          ...item,
          key: item._id,
        };
      });
      return {
        ...state,
        cityTableData: result,
        total: action.payload.total,
      };
    },

    open(state, action) {
      return {
        ...state,
        isModalVisible: true,
      };
    },
    close(state, action) {
      return {
        ...state,
        isModalVisible: false,
      };
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/admin/city') {
          dispatch({
            type: 'getTableDataAsync',
            payload: {
              page_size: 10,
              current_page: 1,
            },
          });
        }
      });
    },
  },
};

export default IndexModel;
